import { Tag } from 'antd';
import React, { useEffect, useState } from 'react';

interface Role {
  id: string;
  name: string;
}

interface Props {
  roleIdString: string;
  roles: Role[];
}

const RoleTags: React.FC<Props> = (props) => {
  const [roleNames, setRoleNames] = useState<string[]>([]);

  useEffect(() => {
    if (!props.roleIdString) {
      setRoleNames([]);
      return;
    }
    const roleIds = props.roleIdString.split(',').map((id) => id.trim());
    const names = roleIds
      .map((id) => props.roles.find((role) => role.id === id))
      .filter((role) => role !== undefined)
      .map((role) => role!.name);

    setRoleNames(names);
  }, [props.roleIdString, props.roles]);

  return (
    <div>
      {roleNames.map((name, index) => (
        <Tag key={index}>{name}</Tag>
      ))}
    </div>
  );
};

export default RoleTags;
